#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "../include/network_monitor.h"

#define PROC_NET_DEV "/proc/net/dev"
#define MAX_LINE_LENGTH 256

static pthread_t monitor_thread;
static Network_Stats current_stats = {0};
static pthread_mutex_t stats_mutex = PTHREAD_MUTEX_INITIALIZER;
static Network_Monitor_Args* monitor_args = NULL;

// 读取网络接口统计信息
static int read_network_stats(Network_Stats* stats) {
    FILE* fp;
    char line[MAX_LINE_LENGTH];
    unsigned long long rx_bytes, tx_bytes, rx_packets, tx_packets;
    
    fp = fopen(PROC_NET_DEV, "r");
    if (!fp) {
        return -1;
    }
    
    // 跳过前两行（标题行）
    fgets(line, sizeof(line), fp);
    fgets(line, sizeof(line), fp);
    
    // 重置统计值
    stats->rx_bytes = 0;
    stats->tx_bytes = 0;
    stats->rx_packets = 0;
    stats->tx_packets = 0;
    
    // 读取所有网络接口的统计信息
    while (fgets(line, sizeof(line), fp)) {
        if (sscanf(line, "%[^:]: %llu %llu %*u %*u %*u %*u %*u %*u %llu %llu",
                   stats->name, &rx_bytes, &rx_packets, &tx_bytes, &tx_packets) == 5) {
            // 只统计物理接口（排除lo接口）
            if (strncmp(stats->name, "lo", 2) != 0) {
                stats->rx_bytes += rx_bytes;
                stats->tx_bytes += tx_bytes;
                stats->rx_packets += rx_packets;
                stats->tx_packets += tx_packets;
            }
        }
    }
    
    fclose(fp);
    return 0;
}

// 网络监控线程函数
void* network_monitor_thread(void* arg) {
    Network_Monitor_Args* args = (Network_Monitor_Args*)arg;
    Network_Stats prev_stats = {0};
    Network_Stats curr_stats = {0};
    
    // 首次读取统计信息
    if (read_network_stats(&prev_stats) < 0) {
        return NULL;
    }
    
    while (args->running) {
        sleep(args->interval);
        
        // 读取当前统计信息
        if (read_network_stats(&curr_stats) < 0) {
            continue;
        }
        
        // 计算速度
        double interval = args->interval;
        curr_stats.rx_speed = (curr_stats.rx_bytes - prev_stats.rx_bytes) / (1024.0 * interval);
        curr_stats.tx_speed = (curr_stats.tx_bytes - prev_stats.tx_bytes) / (1024.0 * interval);
        
        // 更新统计信息
        pthread_mutex_lock(&stats_mutex);
        current_stats = curr_stats;
        pthread_mutex_unlock(&stats_mutex);
        
        // 保存当前值作为下一次的前值
        prev_stats = curr_stats;
    }
    
    return NULL;
}

// 初始化网络监控
int init_network_monitor(void) {
    monitor_args = malloc(sizeof(Network_Monitor_Args));
    if (!monitor_args) {
        return -1;
    }
    
    monitor_args->interval = 1;  // 默认1秒更新一次
    monitor_args->running = 1;
    
    if (pthread_create(&monitor_thread, NULL, network_monitor_thread, monitor_args) != 0) {
        free(monitor_args);
        monitor_args = NULL;
        return -1;
    }
    
    return 0;
}

// 清理网络监控
void cleanup_network_monitor(void) {
    if (monitor_args) {
        monitor_args->running = 0;
        pthread_join(monitor_thread, NULL);
        free(monitor_args);
        monitor_args = NULL;
    }
    
    pthread_mutex_destroy(&stats_mutex);
}

// 获取当前网络统计信息
Network_Stats get_network_stats(void) {
    Network_Stats stats;
    
    pthread_mutex_lock(&stats_mutex);
    stats = current_stats;
    pthread_mutex_unlock(&stats_mutex);
    
    return stats;
} 